package com.pdf.pdfserver.service.read.text;

import com.pdf.pdfserver.enums.FileSuffixEnum;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @Author songfz
 * @Description
 * @Date 2022/1/4
 */
@Service
public class PdfReadService implements IfReadService {

    private static Logger LOG = LoggerFactory.getLogger(PdfReadService.class);

    @Override
    public String read(FileSuffixEnum suffixEnum, InputStream fis) {
        PDDocument ex = null;
        try {
            ex = PDDocument.load(fis);
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(ex);
        } catch (IOException e) {
        LOG.error(e.getMessage(),e);
        } finally {

            Optional.ofNullable(ex).ifPresent(ex1 -> {
                        try {
                            ex1.close();
                        } catch (IOException e) {
                            LOG.error(e.getMessage(), e);
                        }
                    }
            );
            Optional.ofNullable(fis).ifPresent(in1-> {
                try {
                    in1.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(),e);
                }
            });
        }
        return null;
    }
}
